import { lazy, useEffect, useState } from "react";
import { RouteObject, useRoutes } from "react-router-dom";
import routes from "@/config/routes";
// import {
//   DesktopOutlined,
//   FileOutlined,
//   PieChartOutlined,
//   TeamOutlined,
//   UserOutlined,
// } from "@ant-design/icons";
import { filterRoute } from "./handleRoute";
import { authRouter } from "./auth/frontendAuth";
import store from "@/store";
import { RoutesMap } from "@/model/routesMap";
import { getStorage } from "@/utils/utils";
const Empty = lazy(() => import("@/views/empty"));
type Router = RouteObject & {
  meta?: any;
  children?: any;
};
const roles = getStorage("ROLE") && [...JSON.parse(getStorage("ROLE"))];
// 返回是否该菜单是否有权限
const getAuth = (route: RoutesMap) => {
  let isAuth: boolean;
  const role = route.meta && route.meta.role;
  if (typeof role == "string") {
    isAuth = role.includes(role);
  } else if (Array.isArray(role)) {
    isAuth = role.some((e) => roles.includes(e));
  } else if (!route.meta.role) {
    isAuth = true;
  }
  return isAuth;
};
// 判断权限
const auth = (route: RoutesMap) => {
  if (route.meta) {
    const isAuth = getAuth(route);
    if (isAuth) {
      if (route.children && route.children.length) {
        route.children = handAuthRouter(route.children);
      }
      return route;
    }
  }
};
// 菜单处理
const handAuthRouter = (routes: Array<RoutesMap>) => {
  const res = routes.map((item, index) => {
    return auth(item);
  });
  return res.filter((item) => item);
};
export const getRoutes = () => {
  // 将字符串分割数组
  const arr = Object.keys(routes).map((item) => item.split("."));
  const routeTree = filterRoute(arr);
  return handAuthRouter(routeTree);
};

const RouteTable: Router[] = [
  {
    path: "*",
    element: <Empty />,
  },
];
const route = authRouter(RouteTable);
console.log(route);
export default () => useRoutes(route);
